package buaa.paas.controller;

import buaa.paas.dao.ImageMapper;
import buaa.paas.kubectl.DockerUtil;
import buaa.paas.model.Image;
import buaa.paas.model.ImageInfo;
import buaa.paas.model.Response;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.BuildImageResultCallback;
import com.github.dockerjava.api.command.PullImageResultCallback;
import com.github.dockerjava.api.model.PullResponseItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

@CrossOrigin(origins = {"http://localhost:8080","null"})
@RestController
@RequestMapping("/Image")
public class ImageController {
    @Autowired
    ImageMapper imageMapper;

    @Autowired
    DockerUtil dockerUtil;

    @PostMapping("/upload")
    public Response uploadFile(@RequestParam("uid") Integer uid,
                               @RequestParam("name") String name,
                               @RequestParam("tag") String tag,
                               @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) return new Response(400, "上传失败", null);

        // 路径待确认
        String path = "/home/ubuntu/";
        File dest = new File(path + name);

        try {
            file.transferTo(dest);

            dockerUtil = new DockerUtil();
            DockerClient client = dockerUtil.getClient();
            String imageId = client.buildImageCmd(dest).withTag(tag).exec(new BuildImageResultCallback()).awaitImageId();
            if (imageId == null) return new Response(400, "生成镜像失败", null);

            Image image = new Image();
            image.setImageID(imageId);
            // 需要调整
            image.setRepository("82.157.21.193" + path + name);
            image.setName(name);
            image.setTag(tag);

            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            image.setCreateTime(formatter.format(calendar.getTime()));

            image.setUserID(uid);

            imageMapper.createImage(image);

            return new Response(200, "上传成功", image.getImageID());
        } catch (IOException e) {
            e.printStackTrace();
            return new Response(400, "上传失败", null);
        }
    }

    @PostMapping("/delete")
    public Response deleteImage(@RequestParam("imageId") String imageId) {
        dockerUtil = new DockerUtil();
        DockerClient client = dockerUtil.getClient();
        client.removeImageCmd(imageId);

        imageMapper.deleteImage(imageId);

        return new Response(200, "删除成功", null);
    }

    @PostMapping("/pull")
    public Response pullImage(@RequestParam("uid") Integer uid,
                              @RequestParam("repository") String repository,
                              @RequestParam("imageName") String imageName,
                              @RequestParam("tag") String tag) {
        dockerUtil = new DockerUtil();
        DockerClient client = dockerUtil.getClient();
        client.pullImageCmd(repository);

        System.out.println("good1");

        Image image = new Image();

        boolean flag = false;
        List<com.github.dockerjava.api.model.Image> list = client.listImagesCmd().exec();
        for (com.github.dockerjava.api.model.Image i : list) {
            if (imageMapper.findImageById(i.getId()) == null) {
                image.setImageID(i.getId());
                flag = true;
                break;
            }
        }
        if (!flag) return new Response(400, "拉取失败", null);

        System.out.println("good2");

        // 指定一下
        image.setRepository(repository);
        image.setName(imageName);
        image.setTag(tag);

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        image.setCreateTime(formatter.format(calendar.getTime()));

        image.setUserID(uid);

        imageMapper.createImage(image);

        return new Response(200, "拉取成功", null);
    }

    @PostMapping("/getImages")
    public Response getImages(@RequestParam("uid") Integer uid) {
        dockerUtil = new DockerUtil();
        DockerClient client = dockerUtil.getClient();

        List<com.github.dockerjava.api.model.Image> list = client.listImagesCmd().exec();
        if (list.isEmpty()) return new Response(400, "镜像为空", null);

        List<ImageInfo> iList = new ArrayList<>();
        for (com.github.dockerjava.api.model.Image i : list) {
            Image image = imageMapper.findImageById(i.getId());
            if (image == null) return new Response(400, "获取失败", null);
            else if (image.getUserID() != uid) continue;
            ImageInfo info = new ImageInfo();
            info.setRepository(image.getRepository());
            info.setImageName(image.getName());
            info.setTag(image.getTag());
            info.setImageId(i.getId());
            info.setCreateTime(image.getCreateTime());
            info.setSize(i.getSize());
            iList.add(info);
        }
        return new Response(200, "获取成功", iList);
    }
}

